﻿using System.Text;

namespace BlazorAdmin.Tcp.Protocol
{
    /// <summary>
    /// 数据编码转换器
    /// </summary>
    public static class DataEncoder
    {
        /// <summary>
        /// 将字节数组按十六进制输出字符串
        /// </summary>
        /// <param name="buffer">字节缓存区</param>
        /// <param name="start">开始位置</param>
        /// <param name="count">读取数量</param>
        /// <returns></returns>
        public static string ToHexString(this byte[] buffer, int start, int count, string split = "")
        {
            if (buffer.Length < start + count)
                return string.Empty;

            StringBuilder sb = new();
            for (int i = start; i < start + count; i++)
            {
                sb.AppendFormat("{0:X2}{1}", buffer[i], split);
            }

            return sb.ToString();
        }

        /// <summary>
        /// 将字节数组按十六进制输出字符串
        /// </summary>
        /// <param name="buffer">字节缓存区</param>
        /// <param name="start">开始位置</param>
        /// <param name="count">读取数量</param>
        /// <returns></returns>
        public static string ToIntString(this byte[] buffer, int start, int count, string split = "")
        {
            int total = start + count;
            if (buffer.Length < total)
                return string.Empty;

            StringBuilder sb = new();
            for (int i = start; i < total; i++)
            {
                sb.AppendFormat("{0}{1}", buffer[i], i == total - 1 ? "" : split);
            }

            return sb.ToString();
        }

        /// <summary>
        /// 将字节数组转换
        /// </summary>
        /// <param name="buffer">字节缓存区</param>
        /// <param name="start">开始位置</param>
        /// <param name="count">读取数量</param>
        /// <param name="isReserve">是否倒序</param>
        /// <returns></returns>
        public static int ToInt(this byte[] buffer, int start, int count, bool isReserve = true)
        {
            int len = sizeof(int);
            if (count < len || buffer.Length < start + count)
                return 0;
            int value = 0;
            int total = start + count;

            if (isReserve)
            {
                for (int i = 0, j = total - 1; i < count; i++, j--)
                {
                    byte b = buffer[j];
                    value |= b << (i * 8);
                }
            }
            else
            {
                for (int i = start, j = 0; i < total; i++, j++)
                {
                    byte b = buffer[i];
                    value |= b << (j * 8);
                }
            }

            return value;
        }
    }
}
